package com.kuang.gulimall.cart.interceptor;

import com.kuang.common.constant.AuthServerConstant;
import com.kuang.common.constant.CartConstant;
import com.kuang.common.vo.MemberRespVo;
import com.kuang.gulimall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


/*
* 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
* */
public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    //业务执行之前的拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();
        //这时候的session已经是从redis中获取的了
        HttpSession session = request.getSession();
        MemberRespVo loginUser = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser != null){
            //用户登录
            userInfoTo.setUserId(loginUser.getUsername());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {

                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    //给cookie分配成功，那就是临时用户，标志位
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //如果最开始user-key是空的话，就是没有临时用户，给一个uuid分配为临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //在目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    //业务执行之后,给临时用户分配，让系统保存
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()){
            //只延长临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            //作用域
            cookie.setDomain("gulimall.com");
            //过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
